<?php

namespace addons\TinyShare\services;

use Yii;
use yii\data\Pagination;
use yii\db\ActiveQuery;
use yii\db\Expression;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use common\helpers\ArrayHelper;
use common\enums\SortEnum;
use common\components\Service;
use common\enums\StatusEnum;
use common\helpers\StringHelper;
use addons\TinyShare\common\models\ShareContent;
use addons\TinyShare\common\models\forms\ContentSearch;

/**
 * Class ContentService
 * @package addons\TinyShare\services
 * @author jackey <270499458@qq.com>
 */
class ContentService extends Service
{
    /**
     * @param ContentSearch $search
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getListBySearch(ContentSearch $search,$member_id)
    {
        $order = ArrayHelper::merge($search->getOrderBy(), ['sort asc', 'id desc']);

        // 所有下级分类
        $cate_ids = [];
        if ($cate_id = $search->cate_id) {
            $cate_ids = Yii::$app->tinyShareService->cate->findChildIdsById($cate_id);
        }

        $data = ShareContent::find()
            ->where(['status' => StatusEnum::ENABLED])
            ->andFilterWhere(['merchant_id' => $this->getMerchantId()])
            ->andFilterWhere(['like', 'name', $search->keyword])
            ->andFilterWhere(['in', 'cate_id', $cate_ids])
			->andWhere(new Expression('(position & '.$search->position.')  > 0'));
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $search->page_size, 'validatePage' => false]);
        $models = $data->offset($pages->offset)
            ->orderBy(implode(',', $order))
            ->with(['like' => function(ActiveQuery $query) use ($member_id) {
                return $query->andWhere(['member_id' => $member_id]);
            },'collection' => function(ActiveQuery $query) use ($member_id) {
                return $query->andWhere(['member_id' => $member_id]);
            }])
            ->asArray()
            ->limit($pages->limit)
            ->all();

		foreach($models as $k=>$v){
			$models[$k]['cover']=@unserialize($models[$k]['cover']);
		}

        return $models;
    }

    
}